import React, { Component } from 'react';
import {
  Card,
  Button,
  Row,
  Col,
  Icon,
  Tabs,
  Table,
  Radio,
  DatePicker,
  Tooltip,
  Menu,
  Dropdown,
  Input,
  Divider,
  Popconfirm,
} from 'antd';
import { connect } from 'dva';
const { MonthPicker, RangePicker } = DatePicker;
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import numeral from 'numeral';
import { formatMessage, FormattedMessage } from 'umi/locale';
import moment from 'moment';

// import { Link } from 'react-router-dom';

import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

const { Search, TextArea } = Input;

import {
  ChartCard,
  MiniArea,
  MiniBar,
  MiniProgress,
  Field,
  Bar,
  Pie,
  TimelineChart,
} from '@/components/Charts';

const { Meta } = Card;

import Trend from '@/components/Trend';
import styles from './ContactList.less';

import { getValueWithLocalStorage } from '@/utils/authority';
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;

const namespace = 'ContactList';
const userInfo = getValueWithLocalStorage('userinfo');
import router from 'umi/router';
import config from '../../../config/web.config'

// import  Fingerprint2  from 'fingerprintjs2'

const mapStateToProps = state => {
  const contactList = state[namespace].contactList;
  const total = state[namespace].total;
  const isLoading = state[namespace].isLoading;

  return {
    contactList,
    total,
    isLoading,
  };
};

const mapDispatchToProps = dispatch => {
  return {
    getContactsList: (_key, _state, _page, _pagesize, _insertTime, _owner,_isVip) => {
      const action = {
        type: `${namespace}/getContactsList`,
        payload: {
          key: _key,
          state: _state,
          page: _page,
          pagesize: _pagesize,
          insertTime: _insertTime,
          owner: _owner,
          isVip:_isVip,
        },
      };
      dispatch(action);
    },

    delContact: (_id, _key, _state, _page, _pagesize, _insertTime, _owner,_isVip) => {
      const action = {
        type: `${namespace}/delContact`,
        payload: {
          id: _id,
          key: _key,
          state: _state,
          page: _page,
          pagesize: _pagesize,
          insertTime: _insertTime,
          isVip:_isVip,
          owner: _owner,
        },
      };
      dispatch(action);
    },

  };
};

@connect(
  mapStateToProps,
  mapDispatchToProps
)
export default class ContactList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      state: '-1', //维修状态:0维修中 1待结账 2已完成 3已取消
      page: '0',
      pagesize: '20',
      insertTime: moment().format('YYYY-MM-DD HH:mm:ss'),
      owner: userInfo.tel,
      key: '',
      isVip:'-1'
    };
  }

  componentDidMount() {
    config.loadlCNZZ()
    this.reloadData();

    // if (window.requestIdleCallback) {
    //   requestIdleCallback(function () {
    //     Fingerprint2.get(function (components) {
    //       var values = components.map(function (component) { return component.value })
    //       var murmur = Fingerprint2.x64hash128(values.join(''), 31)
    //       console.log(murmur)
    //     })
    //   })
    // } else {
    //   setTimeout(function () {
    //     Fingerprint2.get(function (components) {
    //       var values = components.map(function (component) { return component.value })
    //       var murmur = Fingerprint2.x64hash128(values.join(''), 31)
    //       console.log(murmur)
    //     })
    //   }, 500)
    // }

  }

  reloadData = () => {
    this.props.getContactsList(
      this.state.key,
      this.state.state,
      this.state.page,
      this.state.pagesize,
      this.state.insertTime,
      this.state.owner,
      this.state.isVip,
    );
  };


  render() {
    const columns = [
      {
        title: '头像',
        dataIndex: 'headurl',
        key: 'headurl',
        render: (text, record) => (
          <img
            className={styles.cell_headurl}
            src={config.HttpUrl+'/file/pic/' + ((record.headurl == undefined || record.headurl == null)?'': (record.headurl.indexOf('.png')== -1 ?record.headurl+'.png':record.headurl))}
            // src={'http://127.0.0.1:18080/file/pic/' + record.headurl}
          />
        ),
      },
      {
        title: '登记时间',
        dataIndex: 'date',
        key: 'date',
        width: 100,
        render: (text, record) => (
          <span className={styles.no_vip}>
            {record.date.substring(0,10)}
          </span>
        ),
      },
      {
        title: '车主名',
        dataIndex: 'name',
        key: 'name',
        width: 80,
      },
      {
        title: '绑定小程序',
        dataIndex: 'isbindweixin',
        key: 'isbindweixin',
        width: 100,
      },
      {
        title: '会员身份',
        dataIndex: 'isVip',
        key: 'isVip',
        width: 100,
        render: (text, record) => (
          <span className={record.isVip == '1'?styles.vip:styles.no_vip}>
            {record.isVip == '1' ? '会员':'普通'}
          </span>
        ),
      },
      {
        title: '车牌号码',
        dataIndex: 'carcode',
        key: 'carcode',
        width: 100,
      },
      {
        title: '手机号码',
        dataIndex: 'tel',
        key: 'tel',
        width: 100
      },
      {
        title: '车型',
        dataIndex: 'cartype',
        key: 'cartype',
        width: 100
      },
      {
        title: '上牌时间',
        dataIndex: 'carregistertime',
        key: 'carregistertime',
        width: 100,
      },
      {
        title: '下次年审',
        dataIndex: 'yearchecknexttime',
        key: 'yearchecknexttime',
        width: 100,
      },
      {
        title: '保险公司',
        dataIndex: 'safecompany',
        key: 'safecompany',
        width: 100,
      },
      {
        title: '保险到期',
        dataIndex: 'safenexttime',
        key: 'safenexttime',
        width: 100,
      },
      {
        title: 'vin',
        dataIndex: 'vin',
        key: 'vin',
        width: 150,
      },
      {
        title: '最近一次入店',
        dataIndex: 'lastentertime',
        key: 'lastentertime',
        width: 120,
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        width: 150,
        render: (text, record) => (
          <Route>
            <span>
              <Link to={{ pathname: '/contact/addOrEdit', query: { ...record } }}>编辑</Link>
              <Divider type="vertical" />
              <Popconfirm
                   title="确认删除此客户?"
                   onConfirm={() => {
                     this.props.delContact(
                       record._id,
                       this.state.key,
                       this.state.state,
                       this.state.page,
                       this.state.pagesize,
                       this.state.insertTime,
                       this.state.owner,
                       this.state.isVip,);
                   }}
                   okText="确认"
                   cancelText="取消"
                 >
                <a href="#" className={styles.delBtnStyle}>
                  删除
                </a>
              </Popconfirm>
            </span>
          </Route>
        ),
      },
    ];

    const dateFormat = 'YYYY-MM-DD';

    var that = this;

    const extraContent = (
      <div className={styles.extraContent}>
        <RadioGroup
          defaultValue={'-1'}
          onChange={e => {
            if (e.target.value == '-1') {
            } else if (e.target.value == '0') {
            } else if (e.target.value == '1') {
            } else if (e.target.value == '2') {
            } else if (e.target.value == '3') {
            } else if (e.target.value == '4') {
            }

            that.setState({ isVip: e.target.value }, () => {
              that.reloadData();
            });
          }}
        >
          <RadioButton value="-1">全部</RadioButton>
          <RadioButton value="0">普通</RadioButton>
          <RadioButton value="1">Vip</RadioButton>
        </RadioGroup>

        <Search className={styles.extraContentSearch}
                placeholder="输入客户名，手机号，车牌号查询"
                enterButton
                all
                onSearch={(v,e)=>{
                  that.setState({key:v},()=>{
                    that.reloadData()
                  })
                }} />
        <Link className={styles.addBtn} to={{ pathname: '/contact/addOrEdit'}}>新增客户</Link>
      </div>
    );

    return (
      <Card
        bordered={false}
        title={'客户列表'}
        style={{ marginTop: 24 }}
        bodyStyle={{ padding: '0 0px 0px 0px' }}
        extra={extraContent}
      >


        <Table
          columns={columns}
          rowSelection={{
            onSelect: (record, selected, selectedRows, nativeEvent) => {
              alert(record + selected + selectedRows + nativeEvent);
            },
          }}
          pagination={{
            current: Number(this.state.page) + 1,
            loading: this.props.isLoading,
            pageSize: Number(this.state.pagesize),
            showSizeChanger: true,
            showQuickJumper: true,
            pageSizeOptions: ['1', '5', '10', '20', '50'],
            total: this.props.total,
            onShowSizeChange: (current, size) => {
              that.setState({ pagesize: size, page: 0 }, () => {
                that.reloadData();
              });
            },
            onChange: (page, pageSize) => {
              that.setState({ page: page - 1 }, () => {
                that.reloadData();
              });
            },
            showTotal: total => `总计 ${total} 条`,
          }}
          dataSource={this.props.contactList}
        />
      </Card>
    );
  }
}
